#!/user/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Sjy
Description: 导入分析模型
"""

__all__ = []

import json
import copy
from PyQt5 import QtCore, QtWidgets, QtGui

import gui.controls.envs as envs
from ..actions import Actions

global SHOW_DLG
SHOW_DLG = None


class ImportAnalysisModel(QtWidgets.QDialog):
    sigOnSave = QtCore.pyqtSignal(dict)
    sigOnRunParamsModeling = QtCore.pyqtSignal(dict)

    def __init__(self, parent=None):
        super().__init__(parent)
        global SHOW_DLG
        if SHOW_DLG != None:
            return
        SHOW_DLG = self
        self.ui = _UI()
        self.ui.setupUi(self)
        self.ui.sigOnSave.connect(self.on_save)
        self.ui.sigOnRunParamsModeling.connect(self.on_run_params_modeling)
        # self.ui.sigOnCancel.connect(lambda: self.close())
        self.finished.connect(self.closeDialog)
        self.init()
        self.show()

    def init(self, data: dict = {}):
        self.ui._init(copy.deepcopy(data))

    def on_save(self, data: dict = {}):
        self.close()
        sendData = {}
        if data.get("mainModelPath"):
            sendData["mainModelPath"] = data.get("mainModelPath") or ""
        if data.get("subModelPath"):
            sendData["subModelPath"] = data.get("subModelPath") or ""
        self.sigOnSave.emit(sendData)

    def closeDialog(self):
        # 禁用所有信号 关闭对话框后再次打开时会出现问题
        global SHOW_DLG
        SHOW_DLG = None
        self.deleteLater()  # 确保对象被正确删除  这个才能具体删掉不会留残影

    def on_run_params_modeling(self, data: dict = {}):
        self.accept()
        self.sigOnRunParamsModeling.emit(data)


class _UI(QtWidgets.QWidget):
    sigOnSave = QtCore.pyqtSignal(dict)
    sigOnRunParamsModeling = QtCore.pyqtSignal(dict)

    # sigOnCancel = QtCore.pyqtSignal()
    def __init__(self):
        super().__init__()
        self.parent = None
        self.__data = {}

    # 自定义消息
    def setupUi(self, parent):
        # 纵向布局
        self.parent = parent
        self.__ui = envs.UIForm.UiCustomForm(self.__get_ui_config(parent))
        self.__ui._setup_ui(parent)
        # 自适应界面大小
        parent.adjustSize()

    def _init(self, data: dict = {}) -> None:
        self.__data = data
        self.__ui._sets(data)

    def __get_ui_config(self, parent) -> json:
        return {
            "title": "导入分析模型",
            "icon": "icon.png",  # window icon
            # "objectName": "", # window objectName
            "layout": {
                "margin": [10, 10, 10, 10],
                "space": 10,
                "objectName": "qLayout",
            },
            "items": [
                {  # 主模型路径 是 inp 文件
                    "type": "file",
                    "key": "mainModelPath",
                    "typeParams": {
                        "title": "主模型路径",
                        "fileType": "INP Files (*.inp);;CAE Files (*.cae)",
                    },
                    "styleParams": {
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "minWidth": 400,
                    },
                    # 补充组件用来显示模型
                    "onLayoutAppendWidget": lambda layout: self.__init_show_model(
                        layout
                    ),
                },
                {  # 子模型路径
                    "type": "file",
                    "key": "subModelPath",
                    "typeParams": {
                        "title": "子模型路径",
                        "fileType": "INP Files (*.inp);;CAE Files (*.cae)",
                    },
                    "styleParams": {
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "minWidth": 400,
                    },
                    "onLayoutAppendWidget": lambda layout: self.__init_show_model(
                        layout
                    ),
                },
                # 接下来是底部的 确定和取消按钮
                {},
                {
                    "type": "tools",
                    "typeParams": {
                        "items": [
                            {
                                "title": "参数化建模",
                                "action": lambda: self.__run_params_modeling(),
                            },
                            {
                                "title": "确定",
                                "action": lambda: self.__on_save(),
                            },
                            {
                                "title": "取消",
                                "action": lambda: self.parent.close(),
                            },
                        ],
                    },
                    "styleParams": {  # 控制样式的参数
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                    },
                },
            ],
        }

    def __run_params_modeling(self):
        """点击启动参数化建模对话框"""
        info = self.__ui._gets() or {}
        data = info.get("data") or {}
        # 主模型应该是必填的
        mainModelPath = data.get("mainModelPath")
        if not mainModelPath:
            return envs.MBox.warning("请选择主模型文件")
        self.sigOnRunParamsModeling.emit(data)

    def __on_save(self):
        info = self.__ui._gets() or {}
        data = info.get("data") or {}
        # 主模型应该是必填的
        mainModelPath = data.get("mainModelPath")
        # subModelPath = data.get("subModelPath")
        if not mainModelPath:
            return envs.MBox.warning("请选择主模型文件")

        cmd = f"inp_parsing.exe"
        cwd = "module/inp_anlysis"
        envs.apis.pexecute(cmd, cwd=cwd, shell=True, isEmit=True)

        # if not subModelPath:return envs.MBox.warning("请选择主模型对应的计算文件")
        self.sigOnSave.emit(data)

    def __init_show_model(self, layout: QtWidgets.QHBoxLayout = None):
        qbtn = QtWidgets.QPushButton("显示模型")
        layout.addWidget(qbtn)
        # 找到 layout 中 lineEdit widget
        lineEditWidget = layout.itemAt(1).widget()
        # 获取 layout中的文本
        qbtn.clicked.connect(
            lambda *args, widget=lineEditWidget: self.__show_model(widget)
        )

    def __show_model(self, widget: str = ""):
        if not widget:
            return
        # 利用接口文件显示模型
        inpFile = widget.text()
        # 判断文件类型
        if inpFile.lower().endswith(".inp"):
            Actions.show_model(inpFile)
        elif inpFile.lower().endswith(".cae"):
            envs.MBox.warning("系统暂不支持CAE模型的显示")
